import { Request, Response, NextFunction } from 'express';
import { StatusCodes } from 'http-status-codes';
import { CustomError } from '../types/error';
import log from '../utils/logger';

export const ERROR_CODES = {
  // 认证相关错误
  UNAUTHORIZED: StatusCodes.UNAUTHORIZED,
  INVALID_TOKEN: StatusCodes.UNAUTHORIZED,
  TOKEN_EXPIRED: StatusCodes.UNAUTHORIZED,
  
  // 授权相关错误
  FORBIDDEN: StatusCodes.FORBIDDEN,
  INSUFFICIENT_PERMISSIONS: StatusCodes.FORBIDDEN,
  
  // 验证相关错误
  VALIDATION_ERROR: StatusCodes.BAD_REQUEST,
  INVALID_INPUT: StatusCodes.BAD_REQUEST,
  INVALID_FORMAT: StatusCodes.BAD_REQUEST,
  
  // 资源相关错误
  RESOURCE_NOT_FOUND: StatusCodes.NOT_FOUND,
  RESOURCE_ALREADY_EXISTS: StatusCodes.CONFLICT,
  RESOURCE_CONFLICT: StatusCodes.CONFLICT,
  
  // 业务逻辑错误
  BUSINESS_ERROR: StatusCodes.BAD_REQUEST,
  OPERATION_FAILED: StatusCodes.BAD_REQUEST,
  LIMIT_EXCEEDED: StatusCodes.TOO_MANY_REQUESTS,
  
  // 系统错误
  INTERNAL_ERROR: StatusCodes.INTERNAL_SERVER_ERROR,
  DATABASE_ERROR: StatusCodes.INTERNAL_SERVER_ERROR,
  EXTERNAL_SERVICE_ERROR: StatusCodes.BAD_GATEWAY,
  
  // 其他错误
  UNKNOWN_ERROR: StatusCodes.INTERNAL_SERVER_ERROR
} as const;

// 错误处理中间件
export const errorHandler = (
  err: Error,
  _req: Request,
  res: Response,
  _next: NextFunction
) => {
  log.error('Error:', {
    name: err.name,
    message: err.message,
    stack: err.stack
  });

  if (err instanceof CustomError) {
    return res.status(err.code).json({
      success: false,
      ...err.toJSON()
    });
  }

  // 处理验证错误
  if (err.name === 'ValidationError') {
    return res.status(StatusCodes.BAD_REQUEST).json({
      success: false,
      code: StatusCodes.BAD_REQUEST,
      message: '输入验证失败',
      details: err.message
    });
  }

  // 处理JWT错误
  if (err.name === 'JsonWebTokenError') {
    return res.status(StatusCodes.UNAUTHORIZED).json({
      success: false,
      code: StatusCodes.UNAUTHORIZED,
      message: '无效的令牌'
    });
  }

  if (err.name === 'TokenExpiredError') {
    return res.status(StatusCodes.UNAUTHORIZED).json({
      success: false,
      code: StatusCodes.UNAUTHORIZED,
      message: '令牌已过期'
    });
  }

  // 处理MongoDB错误
  if (err.name === 'MongoError' || err.name === 'MongoServerError') {
    // 处理重复键错误
    if ((err as any).code === 11000) {
      return res.status(StatusCodes.CONFLICT).json({
        success: false,
        code: StatusCodes.CONFLICT,
        message: '资源已存在',
        details: err.message
      });
    }
  }

  // 处理其他未知错误
  return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({
    success: false,
    code: StatusCodes.INTERNAL_SERVER_ERROR,
    message: '服务器内部错误',
    ...(process.env.NODE_ENV === 'development' && { details: err.message })
  });
};

// 处理404错误的中间件
export const notFoundHandler = (req: Request, res: Response) => {
  res.status(StatusCodes.NOT_FOUND).json({
    success: false,
    code: StatusCodes.NOT_FOUND,
    message: `未找到路径: ${req.originalUrl}`
  });
};

// 抛出自定义错误的辅助函数
export const throwError = (
  code: StatusCodes,
  message: string,
  details?: Record<string, any>
): never => {
  throw new CustomError(code, message, details);
};
